package com.echo.yixiaowu.main.page

import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.lazy.staggeredgrid.LazyStaggeredGridState
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
import androidx.compose.foundation.lazy.staggeredgrid.items
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import coil3.ImageLoader
import coil3.gif.AnimatedImageDecoder
import coil3.network.okhttp.OkHttpNetworkFetcherFactory
import coil3.request.crossfade
import com.echo.yixiaowu.data.model.WaterfallItem
import com.echo.yixiaowu.data.model.sampleItems
import com.echo.yixiaowu.data.network.NetworkClient
import com.echo.yixiaowu.main.WaterfallItemCard
import com.echo.yixiaowu.route.AppRoute

@Composable
fun OneContentPage(
    gridState: LazyStaggeredGridState,
    modifier: Modifier,
    imageLoader: ImageLoader,
    onNavigate: (AppRoute) -> Unit,
) {
    WaterfallList(
        modifier = modifier,
        state = gridState,
        items = sampleItems,
        imageLoader = imageLoader,
        onNavigate = onNavigate
    )
}

@Composable
fun rememberImageLoader(): ImageLoader {
    val context = LocalContext.current
    return remember {
        ImageLoader.Builder(context).components {
            add(OkHttpNetworkFetcherFactory(NetworkClient.okHttpClient))
                .add(AnimatedImageDecoder.Factory())
        }.crossfade(true).build()
    }
}

@Composable
fun WaterfallList(
    modifier: Modifier = Modifier,
    state: LazyStaggeredGridState,
    items: List<WaterfallItem>,
    imageLoader: ImageLoader,
    onNavigate: (AppRoute) -> Unit,
) {
    val interactionSource = remember { MutableInteractionSource() }
    LazyVerticalStaggeredGrid(
        state = state,
        modifier = modifier,
        columns = StaggeredGridCells.Fixed(2),
        verticalItemSpacing = 10.dp,
        contentPadding = PaddingValues(horizontal = 6.dp, vertical = 8.dp),
        horizontalArrangement = Arrangement.spacedBy(6.dp)
    ) {
        items(items = items, key = { item -> item.id }) { item ->
            WaterfallItemCard(
                item = item,
                modifier = Modifier.clickable(onClick = {
                    onNavigate.invoke(
                        AppRoute.Detail(
                            itemId = item.id,
                            itemType = item.type
                        )
                    )
                }, indication = null, interactionSource = interactionSource),
                imageLoader = imageLoader,
            )
        }
    }
}